{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>
        <i class="bi bi-person-circle me-2"></i>用户详情
    </h2>
    <div class="btn-group">
        <a href="{{ url_for('admin.users') }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i>返回用户列表
        </a>
        {% if user.id != current_user.id %}
        <button class="btn btn-outline-warning" onclick="toggleUserStatus({{ user.id }}, {{ user.username|tojson }}, {{ user.is_active|tojson }})">
            <i class="bi bi-{% if user.is_active %}pause{% else %}play{% endif %} me-1"></i>
            {% if user.is_active %}禁用用户{% else %}启用用户{% endif %}
        </button>
        <button class="btn btn-outline-info" onclick="changeUserRole({{ user.id }}, {{ user.username|tojson }}, {{ user.role|tojson }})">
            <i class="bi bi-person-gear me-1"></i>更改角色
        </button>
        <button class="btn btn-outline-danger" onclick="resetUserPassword({{ user.id }}, {{ user.username|tojson }})">
            <i class="bi bi-key me-1"></i>重置密码
        </button>
        {% endif %}
    </div>
</div>

<!-- 用户基本信息 -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header bg-light">
                <h5 class="mb-0">
                    <i class="bi bi-person-fill me-2"></i>基本信息
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">用户名</label>
                            <div class="fw-bold">{{ user.username }}</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label text-muted">邮箱地址</label>
                            <div class="fw-bold">{{ user.email }}</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label text-muted">真实姓名</label>
                            <div class="fw-bold">{{ user.real_name or '未设置' }}</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">用户角色</label>
                            <div>
                                {% if user.role == 'admin' %}
                                <span class="badge bg-danger fs-6">管理员</span>
                                {% else %}
                                <span class="badge bg-primary fs-6">学生</span>
                                {% endif %}
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label text-muted">班级</label>
                            <div class="fw-bold">
                                {% if user.class_id is not none %}
                                班级 {{ user.class_id }}
                                {% else %}
                                未分配班级
                                {% endif %}
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label text-muted">账户状态</label>
                            <div>
                                {% if user.is_active %}
                                <span class="badge bg-success fs-6">活跃</span>
                                {% else %}
                                <span class="badge bg-secondary fs-6">已禁用</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
                
                <hr>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">注册时间</label>
                            <div class="fw-bold">{{ user.created_at.strftime('%Y年%m月%d日 %H:%M:%S') if user.created_at else '未知' }}</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">最后登录</label>
                            <div class="fw-bold">
                                {% if user.last_login %}
                                {{ user.last_login.strftime('%Y年%m月%d日 %H:%M:%S') }}
                                {% else %}
                                从未登录
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header bg-light">
                <h5 class="mb-0">
                    <i class="bi bi-bar-chart me-2"></i>邮件统计
                </h5>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <div class="border rounded p-3 mb-3">
                            <div class="display-6 text-primary">{{ sent_count }}</div>
                            <small class="text-muted">已发送</small>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="border rounded p-3 mb-3">
                            <div class="display-6 text-success">{{ received_count }}</div>
                            <small class="text-muted">已接收</small>
                        </div>
                    </div>
                </div>
                
                <div class="d-grid gap-2">
                    <a href="{{ url_for('admin.emails', search=user.username) }}" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-envelope me-1"></i>查看相关邮件
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 最近邮件活动 -->
<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header bg-light">
                <h6 class="mb-0">
                    <i class="bi bi-send me-2"></i>最近发送的邮件
                </h6>
            </div>
            <div class="card-body">
                {% if recent_sent %}
                <div class="list-group list-group-flush">
                    {% for email in recent_sent %}
                    <div class="list-group-item px-0">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-1">{{ email.subject[:30] }}{% if email.subject|length > 30 %}...{% endif %}</h6>
                                <p class="mb-1 text-muted small">收件人: {{ email.recipient.username }}</p>
                                <small class="text-muted">{{ email.sent_at.strftime('%m-%d %H:%M') }}</small>
                            </div>
                            <a href="{{ url_for('admin.email_detail', email_id=email.id) }}" 
                               class="btn btn-outline-info btn-sm">
                                <i class="bi bi-eye"></i>
                            </a>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="text-center py-3 text-muted">
                    <i class="bi bi-inbox display-4"></i>
                    <p class="mt-2">暂无发送记录</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card">
            <div class="card-header bg-light">
                <h6 class="mb-0">
                    <i class="bi bi-inbox me-2"></i>最近接收的邮件
                </h6>
            </div>
            <div class="card-body">
                {% if recent_received %}
                <div class="list-group list-group-flush">
                    {% for email in recent_received %}
                    <div class="list-group-item px-0">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-1">{{ email.subject[:30] }}{% if email.subject|length > 30 %}...{% endif %}</h6>
                                <p class="mb-1 text-muted small">发件人: {{ email.sender.username }}</p>
                                <small class="text-muted">{{ email.sent_at.strftime('%m-%d %H:%M') }}</small>
                            </div>
                            <a href="{{ url_for('admin.email_detail', email_id=email.id) }}" 
                               class="btn btn-outline-info btn-sm">
                                <i class="bi bi-eye"></i>
                            </a>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="text-center py-3 text-muted">
                    <i class="bi bi-inbox display-4"></i>
                    <p class="mt-2">暂无接收记录</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 用户状态切换模态框 -->
<div class="modal fade" id="statusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-exclamation-triangle text-warning me-2"></i>确认操作
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="statusModalText"></p>
                <div class="alert alert-warning">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>注意：</strong>此操作将立即生效！
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-warning" onclick="confirmStatusToggle()">确认操作</button>
            </div>
        </div>
    </div>
</div>

<!-- 角色更改模态框 -->
<div class="modal fade" id="roleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-person-gear text-info me-2"></i>更改用户角色
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="roleModalText"></p>
                <div class="mb-3">
                    <label for="newRole" class="form-label">选择新角色</label>
                    <select class="form-select" id="newRole">
                        <option value="student">学生</option>
                        <option value="admin">管理员</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-info" onclick="confirmRoleChange()">确认更改</button>
            </div>
        </div>
    </div>
</div>

<!-- 密码重置模态框 -->
<div class="modal fade" id="passwordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-key text-danger me-2"></i>重置用户密码
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="passwordModalText"></p>
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    <strong>警告：</strong>密码将被重置为默认密码 "123456"，用户需要重新登录！
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmPasswordReset()">确认重置</button>
            </div>
        </div>
    </div>
</div>

<style>
.card-header {
    border-bottom: 1px solid #dee2e6;
}

.badge {
    font-size: 0.8em;
}

.list-group-item {
    border-left: none;
    border-right: none;
}

.list-group-item:first-child {
    border-top: none;
}

.list-group-item:last-child {
    border-bottom: none;
}
</style>

<script>
let currentUserId = null;
let currentUsername = null;
let currentStatus = null;
let currentRole = null;

/**
 * 切换用户状态
 */
function toggleUserStatus(userId, username, isActive) {
    currentUserId = userId;
    currentUsername = username;
    currentStatus = isActive;
    
    const action = isActive ? '禁用' : '启用';
    document.getElementById('statusModalText').textContent = 
        `您确定要${action}用户 "${username}" 吗？`;
    
    const modal = new bootstrap.Modal(document.getElementById('statusModal'));
    modal.show();
}

/**
 * 确认状态切换
 */
function confirmStatusToggle() {
    if (!currentUserId) return;
    
    fetch(`/admin/users/${currentUserId}/toggle_status`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('danger', data.message || '操作失败');
        }
    })
    .catch(error => {
        console.error('切换用户状态时出错:', error);
        showAlert('danger', '操作时发生错误');
    })
    .finally(() => {
        const modal = bootstrap.Modal.getInstance(document.getElementById('statusModal'));
        modal.hide();
        currentUserId = null;
    });
}

/**
 * 更改用户角色
 */
function changeUserRole(userId, username, role) {
    currentUserId = userId;
    currentUsername = username;
    currentRole = role;
    
    document.getElementById('roleModalText').textContent = 
        `当前用户 "${username}" 的角色是 "${role === 'admin' ? '管理员' : '学生'}"`;
    
    document.getElementById('newRole').value = role;
    
    const modal = new bootstrap.Modal(document.getElementById('roleModal'));
    modal.show();
}

/**
 * 确认角色更改
 */
function confirmRoleChange() {
    if (!currentUserId) return;
    
    const newRole = document.getElementById('newRole').value;
    
    fetch(`/admin/users/${currentUserId}/change_role`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ role: newRole })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('danger', data.message || '更改失败');
        }
    })
    .catch(error => {
        console.error('更改用户角色时出错:', error);
        showAlert('danger', '更改时发生错误');
    })
    .finally(() => {
        const modal = bootstrap.Modal.getInstance(document.getElementById('roleModal'));
        modal.hide();
        currentUserId = null;
    });
}

/**
 * 重置用户密码
 */
function resetUserPassword(userId, username) {
    currentUserId = userId;
    currentUsername = username;
    
    document.getElementById('passwordModalText').textContent = 
        `您确定要重置用户 "${username}" 的密码吗？`;
    
    const modal = new bootstrap.Modal(document.getElementById('passwordModal'));
    modal.show();
}

/**
 * 确认密码重置
 */
function confirmPasswordReset() {
    if (!currentUserId) return;
    
    fetch(`/admin/users/${currentUserId}/reset_password`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('success', data.message);
        } else {
            showAlert('danger', data.message || '重置失败');
        }
    })
    .catch(error => {
        console.error('重置密码时出错:', error);
        showAlert('danger', '重置时发生错误');
    })
    .finally(() => {
        const modal = bootstrap.Modal.getInstance(document.getElementById('passwordModal'));
        modal.hide();
        currentUserId = null;
    });
}

/**
 * 显示警告消息
 */
function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 自动移除警告
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 5000);
}
</script>
{% endblock %}